/*
 * Copyright (c) 2009. Silenus Consultoria, S.L.
 */
package es.silenus.detecta.controller;

import es.silenus.detecta.model.ModelCheck;
import es.silenus.detecta.model.User;

import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.sql.DataSource;


/**
 * Analysis controller.
 *
 * @author <a href="mailto:malonso@silenus-consultoria.es">Mariano Alonso</a>
 *
 * @since 22-may-2009 10:45:27
 */
public class AnalysisController extends BaseController {
	/**
	 * The jdbc template;
	 */
	private SimpleJdbcTemplate jdbcTemplate;

	/**
	 * The model checks.
	 */
	private Map<String, ModelCheck> checks;

	/**
	 * Sets the data source.
	 *
	 * @param dataSource the data source.
	 */
	public void setDataSource(DataSource dataSource) {
		if(dataSource == null) {
			this.jdbcTemplate = null;
		} else {
			this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);
		}
	}

	/**
	 * Sets the checks.
	 *
	 * @param checks the checks.
	 */
	public void setChecks(final Map<String, ModelCheck> checks) {
		this.checks = checks;
	}

	/**
	 * Performs a model check.
	 *
	 * @param request the request.
	 * @param response the response.
	 *
	 * @return the view name or null.
	 */
	public String performCheck(final HttpServletRequest request, final HttpServletResponse response) {
		User current = getUser(request);

		String checkName = request.getParameter("name");
		ModelCheck check = checks.get(checkName);

		if(check != null) {
			MapSqlParameterSource args = new MapSqlParameterSource();

			args.addValue("organization", current.getOrganization().getId());

			List<Map<String, Object>> result = jdbcTemplate.queryForList(check.getSQL(), args);

			request.setAttribute("results", result);

			return check.getViewName();
		}

		// TODO: return other error view... check not found
		return null;
	}
}
